#include "file.h"
#include <stdio.h>
int iterate_n_test(LIST *L, char *wo, int okkk)
{
    int ok = 0;
    Tnode *tmp = L -> first;

    for(; tmp != NULL; tmp = tmp -> next)
        if (strcmp(wo, tmp -> word) == 0)
        {
            ok = 1;
            if (okkk)
                tmp -> count += 1;
        }
    return ok;
}


void insert_to_tail(char *pt, int p, LIST *L)
{
    Tnode *tmp;
    tmp = (Tnode *)malloc(sizeof(Tnode));

    strcpy(tmp -> word, pt);
    tmp -> count = 1;
    tmp -> next = NULL;

    if(L -> last != NULL)
    {
        L -> last -> next = tmp;
        L -> last = tmp;
    }

    else
        L -> first = L -> last = tmp;

}

void iterate_n_sort(LIST *L)
{
    Tnode *tmp = L -> first, *tmp1, *k;
    char temp_buffer[SIZE];
    int aux;

    for(; tmp != NULL; tmp = tmp -> next)
    {
        k = tmp;
        for (tmp1 = tmp -> next; tmp1 != NULL; tmp1 = tmp1 -> next)
            if (tmp -> count > tmp1 -> count)
                k = tmp1;

        if (k != tmp)
        {
            aux = tmp -> count;
            tmp -> count = k -> count;
            k -> count = aux;

            strcpy(temp_buffer, tmp -> word);
            strcpy(tmp -> word, k -> word);
            strcpy(k -> word, temp_buffer);
        }
    }

}

void iterate_n_print(LIST *L)
{
    extern fp1;
    int i, v[50], x;
    Tnode *tmp = L -> first;

    for(; tmp != NULL; tmp = tmp -> next)
    {
        fprintf(fp1, tmp -> word);
        fprintf(fp1, "\t");
        x = 0;
        while (tmp -> count > 0)
        {
            v[x] = tmp -> count % 10;
            tmp -> count /= 10;
            ++x;
        }
        for (i = x - 1; i >= 0; --i)
            fputc(v[i] + '0', fp1);

        fprintf(fp1, "\n");
    }
}

